package com.rongshu.view.penpal.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.GlideUtils;
import com.rongshu.view.base.AdapterListener;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.home.bean.LabelResponse;
import com.rongshu.view.penpal.adapter.LabelsAdapter;
import com.rongshu.view.penpal.bean.PenpalDetailsResponse;
import com.rongshu.view.penpal.present.EditPenpalPresenter;
import com.rongshu.view.penpal.view.EditPenpalView;
import com.rongshu.view.penpal.widget.CommentDialog;
import com.rongshu.view.userInfo.activity.CitySelectedActivity;
import com.rongshu.widget.RoundImageView;
import com.rongshu.widget.SelectLabelDialog;
import com.widget.titlebar.ImmersionBar;
import com.widget.titlebar.OnKeyboardListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2018/11/6.
 * description：笔友会管理-编辑资料
 */
public class EditPenpalActivity extends BaseActivity<EditPenpalPresenter> implements EditPenpalView {

    @BindView(R.id.head_middle)
    TextView headMiddle;
    @BindView(R.id.head_right)
    TextView headRight;
    @BindView(R.id.head_content)
    RelativeLayout headContent;
    @BindView(R.id.penpal_logo)
    RoundImageView penpalLogo;
    @BindView(R.id.penpal_name)
    TextView penpalName;
    @BindView(R.id.add_label)
    ImageView addLabel;
    @BindView(R.id.city_content_tv)
    TextView cityContentTv;
    @BindView(R.id.present_input_content)
    EditText presentInputContent;
    @BindView(R.id.present_input_num)
    TextView presentInputNum;
    @BindView(R.id.labels)
    RecyclerView recyclerView;
    @BindView(R.id.main_layout)
    LinearLayout mainLayout;
    private CommentDialog commentDialog;
    private List<LabelResponse.ResponseBean> labels;
    private String picturePath;//头像路径
    private int penpalId;//笔会id
    private List<LabelResponse.ResponseBean> selectedLabels;//选择的标签
    private LabelsAdapter adapter;
    private String imgUrl;
    private int SELECT_CITY = 101;
    private SelectLabelDialog.Builder builder;
    private LabelResponse.ResponseBean custBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset()
                .keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        if (!isPopup && commentDialog != null && commentDialog.isShowing()) {
                            commentDialog.dismiss();
                        }
                    }
                });
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .statusBarAlpha(0);
        } else {
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f);
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_penpal_edit_message;
    }

    @Override
    protected void initView() {
        headMiddle.setText("编辑资料");
        headRight.setText("确定");
        headRight.setTextColor(ContextCompat.getColor(this, R.color.color_3CC051));

        selectedLabels = new ArrayList<>();
        LinearLayoutManager penpalManager = new LinearLayoutManager(this);
        penpalManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(penpalManager);
        adapter = new LabelsAdapter(this, selectedLabels);
        recyclerView.setAdapter(adapter);
        adapter.setAdapterLitener(new AdapterListener() {
            @Override
            public void callBack(Object object) {
                LabelResponse.ResponseBean bean = (LabelResponse.ResponseBean) object;
                if (bean != null) {
                    selectedLabels.remove(bean);
                    if (builder != null) {
                        builder.removeSelect(bean);
                    }
                    if (bean.getId() == 0) {//删除自定义标签
                        custBean = null;
                    }
                    updateAdapter();
                }
            }
        });
        presentInputContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String msg = editable.toString();
                presentInputNum.setText(msg.length() + "/100");
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        penpalId = intent.getIntExtra(Constant.PENPAL_ID, 0);
        setPresenter(new EditPenpalPresenter(this), this);
        presenter.getPenpalDetails(penpalId);
        presenter.getPenpalLabels();
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @OnClick({R.id.head_left, R.id.penpal_logo, R.id.add_label, R.id.label_content,
            R.id.head_right, R.id.city_content, R.id.penpal_name})
    public void onViewClicked(final View view) {
        switch (view.getId()) {
            case R.id.head_left:
                showKeyboard(false);
                finish();
                break;
            case R.id.head_right:
                showKeyboard(false);
                showLoading(true);
                if (TextUtils.isEmpty(picturePath)) {
                    callBackUploadImg(imgUrl);
                } else {
                    presenter.postUploadFileBase64(picturePath);
                }
                break;
            case R.id.penpal_logo:
                presenter.getPicture();
                break;
            case R.id.add_label://添加自定义标签
                if (selectedLabels.size() >= 4) {
                    toast("请选择最多四个标签");
                } else if (presenter.checkIsAddCustomLabel(selectedLabels)) {
                    toast("最多只能添加一个自定义标签");
                } else {
                    penpalName.clearFocus();
                    presentInputContent.clearFocus();
                    commentDialog = new CommentDialog(this);
                    commentDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialogInterface) {
                            showKeyboard(false);
                        }
                    });
                    commentDialog.setSubmitListener(new CommentDialog.submitListener() {
                        @Override
                        public void submit(String msg) {
                            if (!TextUtils.isEmpty(msg.trim())) {
                                custBean = new LabelResponse.ResponseBean();
                                custBean.setId(0);
                                custBean.setTitle(msg.trim());
                                selectedLabels.add(custBean);
                                updateAdapter();
                                commentDialog.dismiss();
                            } else {
                                toast("请输入有效的信息");
                            }
                        }
                    });
                    commentDialog.show();
                }
                break;
            case R.id.label_content:
                if (builder != null) {
                    builder.syncLabel(selectedLabels);
                }
                showLabelPopupWindow();
                break;
            case R.id.city_content:
                Intent intent = new Intent(this, CitySelectedActivity.class);
                startActivityForResult(intent, SELECT_CITY);
                break;
            case R.id.penpal_name:
                toast("名称暂不能修改");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (!TextUtils.isEmpty(selectList.get(0).getCutPath())) {
                    picturePath = selectList.get(0).getCutPath();
                    Glide.with(this)
                            .load(picturePath)
                            .into(penpalLogo);
                }
            } else if (requestCode == SELECT_CITY) {
                if (data != null) {
                    String city = data.getStringExtra(Constant.INTENT_MESSAGE);
                    cityContentTv.setText(city);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        PictureFileUtils.deleteCacheDirFile(this);
        super.onDestroy();
    }

    private void showLabelPopupWindow() {
        if (labels != null) {
            builder = new SelectLabelDialog.Builder(this);
            builder.setDialogClickListener(new SelectLabelDialog.Builder.dialogClickListener() {
                @Override
                public void ClickListener(List<LabelResponse.ResponseBean> tagsList) {
                    selectedLabels.clear();
                    if (custBean != null) {
                        selectedLabels.add(custBean);
                    }
                    for (LabelResponse.ResponseBean bean : tagsList) {
                        if (!selectedLabels.contains(bean)) {
                            selectedLabels.add(bean);
                        }
                    }
                    if (selectedLabels.size() > 4) {
                        toast("请最多选中4个标签");
                        return;
                    }
                    updateAdapter();
                }
            });
            SelectLabelDialog dialog = builder.create();
            builder.setLabels(labels);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    builder.resetLabel();
                }
            });
            dialog.show();
        }
    }

    private void updateAdapter() {
        adapter.notifyDataSetChanged();
        if (selectedLabels.size() >= 4) {
            addLabel.setVisibility(View.GONE);
        } else {
            addLabel.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void callBackPenpalMsg(PenpalDetailsResponse response) {
        if (response != null && response.getResponse() != null) {
            PenpalDetailsResponse.ResponseBean.ModelBean model = response.getResponse().getModel();
            if (model != null) {
                GlideUtils.loadImageView(this, penpalLogo, model.getImg(), R.drawable.penpal_default_logo, R.drawable.penpal_default_logo);
                penpalName.setText(model.getPenclubname());
                cityContentTv.setText(model.getDistrict());
                presentInputContent.setText(model.getSignature());
                imgUrl = model.getImg();
            }
            List<PenpalDetailsResponse.ResponseBean.LabelListBean> labelList = response.getResponse().getLabelList();
            for (PenpalDetailsResponse.ResponseBean.LabelListBean bean : labelList) {
                LabelResponse.ResponseBean labelBean = new LabelResponse.ResponseBean();
                labelBean.setId(bean.getId());
                labelBean.setTitle(bean.getTitle());
                selectedLabels.add(labelBean);
            }
            updateAdapter();
        }
    }

    @Override
    public void callBackLabels(LabelResponse response) {
        labels = response.getResponse();
    }

    @Override
    public void callBackUploadImg(String url) {
        imgUrl = url;
        String selectedLabels = presenter.getSelectedLabels(this.selectedLabels);
        String customLabel = presenter.getSelectedCustomLabel(this.selectedLabels);
        presenter.submitMsg(penpalId,
                cityContentTv.getText().toString(),
                presentInputContent.getText().toString(),
                penpalName.getText().toString(),
                imgUrl,
                selectedLabels, customLabel);
    }

    @Override
    public void callBackSubmitResult() {
        toast("笔友会信息编辑成功");
        showLoading(false);
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void INetFaild(String msg) {
        toast(msg);
        showLoading(false);
    }
}
